package com.yj.web.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.yj.web.dao.mapper.AdminUserMapper;
import com.yj.web.dao.mapper.FundraisingProjectMapper;
import com.yj.web.dao.po.admin.*;
import com.yj.web.help.IdGenerater;
import com.yj.web.help.MsgSender;
import com.yj.web.service.AdminUserService;
import com.yj.web.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by yanlinyang on 2017/7/4.
 */
@Service("adminUserService")
public class AdminUserServiceImpl implements AdminUserService {

    private static final String PREFIX_PIC = "http://api.yinuochoukuan.com/public/previewImg?id=";

    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private FundraisingProjectMapper fundraisingProjectMapper;
    @Autowired
    private MessageService messageService;


    @Override
    public List<AdminUser> listUserPage (String nickname, String idNumber, String phone, String startTime, String endTime, int page, int size) throws Exception {
//        List<AdminUser> users1 = null;
//        List<AdminUser> users2 = null;
//        List<String> ids = new ArrayList<>();
//        int offset = (page - 1) * size;
//        users1 = adminUserMapper.listUserInfoByIdnumRegtime(idNumber, startTime, endTime);
//        for (AdminUser adminUser : users1) {
//            ids.add(adminUser.getUserInfoId());
//        }
//        if (0 == ids.size()) {
//            return null;
//        }
//        users2 = adminUserMapper.listUserByIdPhoneNickname(phone, nickname, ids, offset, size);
//
//        for (AdminUser adminUser2 : users2) {
//            for (AdminUser adminUser1 : users1) {
//                if (adminUser1.getUserInfoId().equals(adminUser2.getUserInfoId())) {
//                    PoUtil.supplementPo(adminUser1, adminUser2);
//                }
//            }
//        }
        int offset = (page - 1) * size;
        List<AdminUser> users = adminUserMapper.listUserInfoByIdnumRegtimePhoneNickname(idNumber, startTime, endTime, phone, nickname, offset, size);

        return users;
    }

    public int countUser(String nickname, String idNumber, String phone, String startTime, String endTime) {
//        List<AdminUser> users1 = new ArrayList<>();
//        users1 =adminUserMapper.listUserInfoByIdnumRegtime(idNumber, startTime, endTime);
//        List<String> ids = new ArrayList<>();
//        for (AdminUser adminUser : users1) {
//            ids.add(adminUser.getUserInfoId());
//        }
//        int count = adminUserMapper.countUserByIdPhoneNickname(phone, nickname, ids);
        int count = adminUserMapper.countUserInfoByIdnumRegtimePhoneNickname(idNumber, startTime, endTime, phone, nickname);
        return count;
    }

    @Override
    public List<AdminUser> listUser (String nickname, String idNumber, String phone, String startTime, String endTime) throws Exception {
//        List<AdminUser> users1 = null;
//        List<AdminUser> users2 = null;
//        List<String> ids = new ArrayList<>();
//        users1 = adminUserMapper.listUserInfoByIdnumRegtime(idNumber, startTime, endTime);
//        for (AdminUser adminUser : users1) {
//            ids.add(adminUser.getUserInfoId());
//        }
//        if (0 == ids.size()) {
//            return null;
//        }
//        users2 = adminUserMapper.listUserByIdPhoneNicknameNoPage(phone, nickname, ids);
//
//        for (AdminUser adminUser2 : users2) {
//            for (AdminUser adminUser1 : users1) {
//                if (adminUser1.getUserInfoId().equals(adminUser2.getUserInfoId())) {
//                    PoUtil.supplementPo(adminUser1, adminUser2);
//                }
//            }
//        }
        List<AdminUser> users = adminUserMapper.listUserInfoByIdnumRegtimePhoneNicknameNoPage(idNumber, startTime, endTime, phone, nickname);
        return users;

    }

    @Override
    public AdminUser findUserById(String id) {
        return adminUserMapper.findUserById(id);
    }

    public Map findAccountInfoById(String id) {
        Map<String, Object> accountInfo = new HashMap<>();

        UserBaseInfo userBaseInfo = adminUserMapper.findUserBaseInfoById(id);
//        String picPath = fundraisingProjectMapper.findPicPath(userBaseInfo.getPortrait());
        if (null != userBaseInfo.getPortrait()) {
            userBaseInfo.setPortrait(PREFIX_PIC + userBaseInfo.getPortrait());
        }

        AccountCapitalInfo accountCapitalInfo = adminUserMapper.findAccountCapitalInfoById(id);
        double receivablePrincipal = adminUserMapper.findReceivablePrincipalById(id);
        double receivableInterest = adminUserMapper.findReceivableInterestById(id);
        accountCapitalInfo.setReceivablePrincipal(receivablePrincipal);
        accountCapitalInfo.setReceivableInterest(receivableInterest);

        ThirdPartyPaymentInfo thirdPartyPaymentInfo = adminUserMapper.findThirdPartyPaymentInfoById(id);
        accountInfo.put("userBaseInfo", userBaseInfo);
        accountInfo.put("accountCapitalInfo", accountCapitalInfo);
        accountInfo.put("thirdPartyPaymentInfo", thirdPartyPaymentInfo);
        return accountInfo;
    }

    //更换银行卡
    public boolean setBankCardNo(String id, String bankCardNo) {
        ThirdPartyPaymentInfo thirdPartyPayment = adminUserMapper.findThirdPartyPaymentInfoById(id);
        thirdPartyPayment.setBankCardNo(bankCardNo);
//        String msg = "［医诺］尊敬的用户" + thirdPartyPayment.getRealName() + "，您的银行卡已成功更换为" + bankCardNo + "。";

        String phone = adminUserMapper.findUserPhoneByUserNo(thirdPartyPayment.getUserNo());
        String templateCode = "SMS_84210001";
        String templateParam = "{\"name\":\""+ thirdPartyPayment.getRealName() +"\", \"bankCardNo\":\""+ bankCardNo +"\"}";
        try {
            MsgSender.sendMsg(phone, templateCode, templateParam);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        Message message = new Message();
        message.setReceiverStr(phone);
        Set<String> receivers = new HashSet<>();
        receivers.add(phone);
        message.setReceivers(receivers);
        message.setNumber(1);
        message.setContent("【医诺筹款】尊敬的用户"+thirdPartyPayment.getRealName()+"，您的银行卡已成功更换为"+bankCardNo+"。");
        message.setStatus(1);
        message.setType(2);
        messageService.insertMessage(message);

        return adminUserMapper.setBankCardNo(thirdPartyPayment);
    }

    public List<InvestRecord> findInvestRecordById(String id, int page, int size) {
        int offset = (page - 1) * size;
        List<InvestRecord> investRecords = adminUserMapper.findInvestRecordById(id, offset, size);
        return investRecords;
    }

    public int countInvestRecordById(String id) {
        int num = adminUserMapper.countInvestRecordById(id);
        return num;
    }

    public List<FundraisingRecord> findFundraisingRecordById(String id, int page, int size) {
        int offset = (page - 1) * size;
        List<FundraisingRecord> fundraisingRecords = adminUserMapper.findFundraisingRecordById(id, offset, size);
        if (null != fundraisingRecords && fundraisingRecords.size() > 0) {
            for (FundraisingRecord fundraisingRecord : fundraisingRecords) {
                double unpaidPrincipal = adminUserMapper.getUnpaidPrincipal(fundraisingRecord.getFundraisingId());
                double unpaidInterest = adminUserMapper.getUnpaidInterest(fundraisingRecord.getFundraisingId());
                fundraisingRecord.setUnpaidPrincipal(unpaidPrincipal);
                fundraisingRecord.setUnpaidInterest(unpaidInterest);
            }
        }
        return fundraisingRecords;
    }

    public int countFundraisingRecordById(String id) {
        int num = adminUserMapper.countFundraisingRecordById(id);
        return num;
    }

    public List<CapitalChange> findCapitalChangeById(String id, int page, int size) {
        int offset = (page - 1) * size;
        List<CapitalChange> capitalChanges = adminUserMapper.findCapitalChangeById(id, offset, size);
        return capitalChanges;

    }

    public int countCapitalChangeById(String id) {
        int num = adminUserMapper.countCapitalChangeById(id);
        return num;
    }

    public boolean updateCapitalChange(String id) {
        boolean flag = adminUserMapper.updateCapitalChange(id);
        return flag;
    }

    public List<DepositWithdraw> listDepositWithdraw(String real_name, String startTime, String endTime, String phone, Integer status, int page, int size) {
        int offset = (page - 1) * size;
        return adminUserMapper.listDepositWithdraw(real_name, startTime, endTime, phone, status, offset, size);
    }

    public int countDepositWithdraw(String real_name, String startTime, String endTime, String phone, Integer status) {
        return adminUserMapper.countDepositWithdraw(real_name, startTime, endTime, phone, status);
    }

    public DepositWithdraw findDepositWithdrawById(String id) {
        return adminUserMapper.findDepositWithdrawById(id);
    }

    public boolean updateDepositWithdrawStatus(String id) {
        DepositWithdraw depositWithdraw = adminUserMapper.findDepositWithdrawById(id);
        adminUserMapper.updateFreezeAmt(depositWithdraw.getUser_no(), depositWithdraw.getCash_amount());

        ProjectTip tip = new ProjectTip();
        tip.setUser_id(adminUserMapper.findUserIdByUserNo(depositWithdraw.getUser_no()));
        String userPhone = adminUserMapper.findUserPhoneByUserNo(depositWithdraw.getUser_no());
        tip.setTitle(userPhone + "提现申请通过");
        //您于**月**日发起的提现已成功。提现金额***元，收款账户尾号：****。
        String createAt = depositWithdraw.getCreated_at();
        String month = createAt.substring(5,7);
        String day = createAt.substring(8, 10);
        String bankCardNo = depositWithdraw.getCash_bank_acc_no();
        tip.setMsg_body(userPhone + "您好，您于"+month+"月"+day+"日发起的提现已成功。提现金额"+depositWithdraw.getCash_amount()+"元，收款账户尾号："+bankCardNo.substring(bankCardNo.length()-4)+"。");
        tip.setFund_project_id("JustForDBConstraintOfNotNull");
        tip.setProject_type(0);
        tip.setMsg_type(1);
        String tipId = IdGenerater.generateId("11");
        tip.setId(tipId);
        fundraisingProjectMapper.insertProjectTip(tip);

        return adminUserMapper.updateDepositWithdrawStatus(id);
    }
}
